module.exports = (app) => {
  const mongoose = app.mongoose;
  mongoose.pluralize(null);
  const Schema = mongoose.Schema;
  const OrderSchema = new Schema(
    {
      userId: {
        ref: "Userinfo",
        required: true,
        type: mongoose.Types.ObjectId,
      },
      // 订单号
      orderNumber: {
        type: String,
      },
      // 备注
      remark: {
        type: String,
        default: "",
      },
      // 支付方式(0:微信支付，1：余额支付)
      payMethod: { type: Number, required: true },
      // 取餐码
      takeMealCode: {
        type: Number,
        default: 1000,
      },
      //   订单类型(0：自提，1：外卖)
      orderType: {
        type: Number,
        required: true,
      },
      //   订单状态（0：待支付，1：待备餐，2：正在备餐，3：配送中，4：待取餐，5：已完成
      OrderStatus: {
        type: Number,
        required: true,
      },
      //   收货地址id
      addressId: {
        type: mongoose.Types.ObjectId,
        ref: "Useraddress",
      },
      phone: {
        type: String,
        required: true,
      },
      //   商品列表
      goods: [
        {
          goodsId: { type: String, required: true },
          categoryId: { type: String, required: true },
          image: { type: String, default: "" },
          quantity: { type: Number, required: true },
          name: { type: String, required: true },
          price: { type: Number, required: true }, //商品单价
          specs: { type: [String], required: true }, //sku 名称
          sid: { type: [String], required: true }, //sku id
        },
      ],
      //   支付金额
      payPrice: {
        type: Number,
      },
      // 商户订单号
      out_trade_no: {
        type: String,
        default: ""
      },
      // 支付状态
      payStatus: {
        type: Number,
        default: 0,//0：待支付，1：支付成功
      }
      // 下单时间（created_at)
    },
    { versionKey: false, timestamps: true }
  );
  OrderSchema.pre("save", function (next) {
    // 生成17位订单号
    this.orderNumber =
      "" + new Date().getTime() + Math.floor(1000 + Math.random() * 9000);
    // 计算总价
    this.payPrice = this.goods.reduce((a, b) => a + b.price * b.quantity, 0);
    next();
  });
  return mongoose.model("Order", OrderSchema);
};
